package com.zxiw.zxedu.recyclerview.group

import android.annotation.SuppressLint
import android.content.Context
import com.zxiw.zxedu.recyclerview.adapter.HelperRecyclerViewHolder


/**
 * @author zhangxiaoming
 * @date 2023/8/18
 * @description
 * <p>描述：提供分组便捷操作,可设置状态的错误页面、空页面、加载中页面、内容页面自由切换</p>
 * 追加页面状态方式，例如格子页面一部分是本地写死的内容，还有一部分在最后面需要网络请求返回，主要针对这种状态。
 */
@SuppressLint("NotifyDataSetChanged")
abstract class GroupedAppendStateRecyclerViewAdapter<T>(context: Context) :
    GroupedStateRecyclerViewAdapter<T>(context) {
    var count = 0
    override var state: Int = STATE_NORMAL
        set(value) {
            field = value
            when (state) {
                STATE_LOADING,
                STATE_EMPTY,
                STATE_ERROR -> {
                    xRecyclerView?.setEnabledScroll(false)
                    count = 1
                }
                STATE_NORMAL -> {
                    xRecyclerView?.setEnabledScroll(true)
                    count = 0
                }
            }
            notifyDataSetChanged()
        }

    override fun getItemCount(): Int {
        return super.getItemCount() + count
    }

    override fun getItemViewType(position: Int): Int {
        if (count == 1 && (position + count) == itemCount) {
            when (state) {
                STATE_LOADING -> return TYPE_LOADING
                STATE_EMPTY -> return TYPE_EMPTY
                STATE_ERROR -> return TYPE_ERROR
            }
        }
        return itemViewType(position)
    }

    override fun onBindViewHolder(viewHolder: HelperRecyclerViewHolder, position: Int) {
        if (count == 1 && (position + count) == itemCount) {
            when (state) {
                STATE_LOADING -> onBindLoadingViewHolder(viewHolder)
                STATE_EMPTY -> onBindEmptyViewHolder(viewHolder)
                STATE_ERROR -> onBindErrorViewHolder(viewHolder)
            }
        } else {
            viewHolder(viewHolder, position)
        }
    }

    /**
     * 追加内容  如果发现有内容追加过来，会自动消掉占位图
     */
    fun addAppendGroups(datas: List<T>?): Boolean {
        val result = super.addGroups(datas!!)
        state = STATE_NORMAL
        return result
    }

    /**
     * 追加内容  如果发现有内容追加过来，会自动消掉占位图
     */
    fun addAppendGroup(data: T): Boolean {
        val result = super.addGroup(data)
        state = STATE_NORMAL
        return result
    }
}